//
//  AFNetWork.m
//  Begin
//
//  Created by dllo on 9/14/15.
//  Copyright (c) 2015 King. All rights reserved.
//

#import "HandleData.h"
#import "AFNetworking.h"

@implementation HandleData

+ (void)handleDataWithUrl:(NSString *)url completion:(void (^)(id data))block
{
    // WiFi边上的 菊花
    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = YES;
    
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"application/json",@"text/javascript",@"text/html",@"text/plain", nil];
    NSString *strPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%lu.aa",strPath,(unsigned long)[url hash]]; // 存入本地的地址
    NSURL *str = [NSURL URLWithString:url];
    /*
     *  @param operation      网络请求成功
     *
     *
     *  @return 写入本地
     */
    [session GET:str.absoluteString parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        // 将AGNetworking 解析结果转换成data
        NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
// 返回数据
        block(responseObject);
        [data writeToFile:path atomically:YES];
        application.networkActivityIndicatorVisible = NO;
        
    }
     
     /*
      *  网络请求失败 读取本地数据
      */

     failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
         
         NSData *data = [NSData dataWithContentsOfFile:path];
         if (data != nil) {
             id data1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
             block(data1);
         }
         application.networkActivityIndicatorVisible = NO;
    }];
    
    
}

@end
